import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { isPathMatch } from '@/utils/validate'
import { isRelogin } from '@/utils/request'
import { LOGOUT_REDIRECT_PATH, SSO_ENTRY_PATH } from '@/constants'

NProgress.configure({ showSpinner: false })

const whiteList = ['/register', SSO_ENTRY_PATH]

const DEFAULT_STATISTICS_ROUTE = '/statistics/statistics'

const isExternalUrl = (url) => /^https?:\/\//.test(url)

const sanitizeStatePath = (fullPath) => {
  if (!fullPath || fullPath === '/' || fullPath === SSO_ENTRY_PATH || fullPath.startsWith('/login'))
  {
    return DEFAULT_STATISTICS_ROUTE
  }
  return fullPath.startsWith('/') ? fullPath : DEFAULT_STATISTICS_ROUTE
}

function redirectToUnifiedLogin(to, next) {
  if (isPathMatch(SSO_ENTRY_PATH, to.path))
  {
    next()
  }
  else
  {
    const targetState = sanitizeStatePath(to?.fullPath)
    next({
      path: SSO_ENTRY_PATH,
      query: { state: targetState }
    })
  }
  NProgress.done()
}

function redirectAfterLogout(next) {
  if (isExternalUrl(LOGOUT_REDIRECT_PATH))
  {
    NProgress.done()
    window.location.href = LOGOUT_REDIRECT_PATH
  }
  else
  {
    NProgress.done()
    next({ path: LOGOUT_REDIRECT_PATH })
  }
}

const isWhiteList = (path) => {
  return whiteList.some(pattern => isPathMatch(pattern, path))
}

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
    /* has token*/
    if (to.path === '/login') {
      next({ path: DEFAULT_STATISTICS_ROUTE }) // 已登录用户访问登录页时定向到大屏，避免落在无效首页
      NProgress.done()
    } else if (isWhiteList(to.path)) {
      next()
    } else {
      if (store.getters.roles.length === 0) {
        isRelogin.show = true
        // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then(() => {
          isRelogin.show = false
          store.dispatch('GenerateRoutes').then(accessRoutes => {
            // 根据roles权限生成可访问的路由表
            router.addRoutes(accessRoutes) // 动态添加可访问路由表
            next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
          })
        }).catch(err => {
            store.dispatch('LogOut').then(() => {
              Message.error(err)
              redirectAfterLogout(next) // 拉取权限失败时按统一逻辑退出
            })
          })
      } else {
        next()
      }
    }
  } else {
    // 没有token，统一跳转到SSO入口完成登录
    redirectToUnifiedLogin(to, next)
    return
  }
})

router.afterEach(() => {
  NProgress.done()
})
